﻿using System;
using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace ArduinoVCXProjUpdater
{
    public class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            

            if (args.Length != 1)
            {

                MessageBox.Show("No input file provided....");
                return;
            }
            FileInfo vcxProjFile = new FileInfo(args[0]);
            if(!vcxProjFile.Extension.ToLower().EndsWith("vcxproj"))
            {
                MessageBox.Show("This is not a vcxproj file.");
                
            }
            if(!vcxProjFile.Exists)
            {

                Console.WriteLine("Input file doesn't exists");
                Console.Read(); return;
            }

           
            UpdateVCXProjFile(vcxProjFile);

            MessageBox.Show("File updated !");


        }

        public static void UpdateVCXProjFile(FileInfo vcxProjFile)
        {
            string additionnalLibs = CreateListOfLibsAsString();
            Console.WriteLine("Updating {0}", vcxProjFile.FullName);
            XmlDocument doc = new XmlDocument();
            doc.Load(vcxProjFile.FullName);

            updateNodes(doc.GetElementsByTagName("LibraryPath"), additionnalLibs);

            updateNodes(doc.GetElementsByTagName("SourcePath"), additionnalLibs);

            updateNodes(doc.GetElementsByTagName("IncludePath"), additionnalLibs);

            doc.Save(vcxProjFile.FullName);
        }

        private static string CreateListOfLibsAsString()
        {
            string libs = "";
            DirectoryInfo di = new DirectoryInfo(LibFolder);

            foreach (var directoryInfo in di.GetDirectories())
            {
                libs += directoryInfo.FullName + ";";
            }
            foreach (var str in Settings.Default.LibrairyList)
            {
                libs += str + ";";
            }

            return libs;
        }

        public static  string LibFolder =  Settings.Default.ArduinoLibrairyPath;

     
        private static void updateNodes(XmlNodeList selectNodes, string libs)
        {
            foreach (XmlNode selectNode in selectNodes)
            {
                selectNode.InnerText = libs;

            }
        }
    }
}
